import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
import { h } from 'vue'
// 路由懒加载
const Layout = () => import('@/views/Layout/Layout.vue') // 布局
const Home = () => import('@/views/home/home.vue')  // 主页
const TopCategory = () => import('@/views/category/top-category.vue') // 商品一级分类
const SubCategory = () => import('@/views/category/sub-category.vue')  // 商品二级分类
const Goods = () => import('@/views/goods/goods.vue')  // 商品详情
const Login = () => import('@/views/login/login.vue') // 登录页
const Cart = () => import('@/views/cart/cart.vue')  // 购物车页面
const PayCheckout = () => import('@/views/member/pay/checkout.vue')  // 结算
const payIndex = () => import('@/views/member/pay/pay.vue') // 支付
const MeberLayout = () => import('@/views/member/Layout') // 个人中心布局
const MemberHome = () => import('@/views/member/home/member-home.vue')  // 个人中心
const MemberOrder = () => import('@/views/member/order/order.vue') // 订单管理
const MemberOrderDetail = () => import('@/views/member/order/detail') // 订单详情
// 路由规则
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', component: Home },
      { path: '/category/:id', component: TopCategory },
      { path: '/category/sub/:id', component: SubCategory },
      { path: '/product/:id', component: Goods },
      { path: '/cart', component: Cart },
      { path: '/member/checkout', component: PayCheckout },
      { path: '/member/pay', component: payIndex },
      {
        path: '/member',
        component: MeberLayout,
        children: [
          { path: '/member', component: MemberHome },
          {
            path: '/member/order',
            // 创建一个RouterView容器形成嵌套关系
            component: { render: () => h(<RouterView />) },
            children: [
              { path: '', component: MemberOrder },
              { path: ':id', component: MemberOrderDetail }
            ]
          }
        ]
      }
    ]
  },
  { path: '/login', component: Login }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior() {
    return { left: 0, top: 0 }
  }
})


// 前置导航守卫
router.beforeEach((to, from, next) => {
  // 用户信息
  const { token } = store.state.user.profile
  // 跳转去member开头的地址却没有登录
  if (to.path.startsWith('/member') && !token) {
    next({ path: '/login', query: { redirectUrl: to.fullPath } })
  }
  next()
})
export default router
